<template>
  <el-dialog
    v-model="dialogVisible"
    :title="getDialogTitle()"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      :disabled="dialogType === 'view'"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="规则名称" prop="ruleName">
            <el-input
              v-model="formData.ruleName"
              placeholder="请输入规则名称"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预警类型" prop="warningType">
            <el-select
              v-model="formData.warningType"
              placeholder="请选择预警类型"
              style="width: 100%"
              @change="handleWarningTypeChange"
            >
              <el-option label="水位预警" value="water_level" />
              <el-option label="流量预警" value="flow" />
              <el-option label="降雨预警" value="rainfall" />
              <el-option label="库容预警" value="capacity" />
              <el-option label="综合预警" value="comprehensive" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="预警级别" prop="warningLevel">
            <el-select
              v-model="formData.warningLevel"
              placeholder="请选择预警级别"
              style="width: 100%"
            >
              <el-option label="蓝色预警" value="blue" />
              <el-option label="黄色预警" value="yellow" />
              <el-option label="橙色预警" value="orange" />
              <el-option label="红色预警" value="red" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio value="active">启用</el-radio>
              <el-radio value="inactive">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 阈值条件配置 -->
      <el-form-item label="阈值条件" prop="thresholdConfig">
        <el-card class="threshold-config" shadow="never">
          <div class="threshold-item" v-for="(condition, index) in formData.thresholdConfig" :key="index">
            <el-row :gutter="10" align="middle">
              <el-col :span="5">
                <el-select v-model="condition.parameter" placeholder="参数">
                  <el-option
                    v-for="param in getParameterOptions()"
                    :key="param.value"
                    :label="param.label"
                    :value="param.value"
                  />
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-select v-model="condition.operator" placeholder="操作符">
                  <el-option label=">" value="gt" />
                  <el-option label=">=" value="gte" />
                  <el-option label="<" value="lt" />
                  <el-option label="<=" value="lte" />
                  <el-option label="=" value="eq" />
                  <el-option label="!=" value="ne" />
                </el-select>
              </el-col>
              <el-col :span="5">
                <el-input v-model="condition.value" placeholder="阈值" />
              </el-col>
              <el-col :span="4">
                <el-input v-model="condition.unit" placeholder="单位" />
              </el-col>
              <el-col :span="4">
                <el-select v-model="condition.logic" placeholder="逻辑" v-if="index < formData.thresholdConfig.length - 1">
                  <el-option label="且" value="and" />
                  <el-option label="或" value="or" />
                </el-select>
              </el-col>
              <el-col :span="2">
                <el-button
                  type="danger"
                  size="small"
                  circle
                  @click="removeThresholdCondition(index)"
                  v-if="formData.thresholdConfig.length > 1"
                >
                  <el-icon><Minus /></el-icon>
                </el-button>
              </el-col>
            </el-row>
          </div>
          <el-button
            type="primary"
            size="small"
            @click="addThresholdCondition"
            style="margin-top: 10px"
          >
            <el-icon><Plus /></el-icon>
            添加条件
          </el-button>
        </el-card>
      </el-form-item>

      <!-- 通知方式 -->
      <el-form-item label="通知方式" prop="notificationMethod">
        <el-checkbox-group v-model="formData.notificationMethod">
          <el-checkbox value="sms">短信</el-checkbox>
          <el-checkbox value="email">邮件</el-checkbox>
          <el-checkbox value="phone">电话</el-checkbox>
          <el-checkbox value="app">APP推送</el-checkbox>
          <el-checkbox value="webhook">Webhook</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <!-- 通知人员 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="通知人员" prop="notificationUsers">
            <el-select
              v-model="formData.notificationUsers"
              multiple
              placeholder="请选择通知人员"
              style="width: 100%"
            >
              <el-option label="张三" value="zhangsan" />
              <el-option label="李四" value="lisi" />
              <el-option label="王五" value="wangwu" />
              <el-option label="赵六" value="zhaoliu" />
              <el-option label="孙七" value="sunqi" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="通知组" prop="notificationGroups">
            <el-select
              v-model="formData.notificationGroups"
              multiple
              placeholder="请选择通知组"
              style="width: 100%"
            >
              <el-option label="管理员组" value="admin" />
              <el-option label="运维组" value="ops" />
              <el-option label="值班组" value="duty" />
              <el-option label="应急组" value="emergency" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 触发条件 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="触发频率" prop="triggerFrequency">
            <el-select
              v-model="formData.triggerFrequency"
              placeholder="请选择触发频率"
              style="width: 100%"
            >
              <el-option label="立即触发" value="immediate" />
              <el-option label="每5分钟" value="5min" />
              <el-option label="每10分钟" value="10min" />
              <el-option label="每30分钟" value="30min" />
              <el-option label="每小时" value="1hour" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="持续时间" prop="duration">
            <el-input
              v-model="formData.duration"
              placeholder="请输入持续时间（分钟）"
              type="number"
            >
              <template #append>分钟</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 生效时间 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="生效开始时间" prop="effectiveStartTime">
            <el-time-picker
              v-model="formData.effectiveStartTime"
              placeholder="选择开始时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生效结束时间" prop="effectiveEndTime">
            <el-time-picker
              v-model="formData.effectiveEndTime"
              placeholder="选择结束时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 高级设置 -->
      <el-form-item label="高级设置">
        <el-collapse>
          <el-collapse-item title="消息模板设置" name="template">
            <el-form-item label="短信模板" prop="smsTemplate">
              <el-input
                v-model="formData.smsTemplate"
                type="textarea"
                :rows="3"
                placeholder="请输入短信模板，支持变量：{ruleName}, {level}, {value}, {time}"
              />
            </el-form-item>
            <el-form-item label="邮件模板" prop="emailTemplate">
              <el-input
                v-model="formData.emailTemplate"
                type="textarea"
                :rows="3"
                placeholder="请输入邮件模板，支持变量：{ruleName}, {level}, {value}, {time}"
              />
            </el-form-item>
          </el-collapse-item>
          <el-collapse-item title="恢复通知设置" name="recovery">
            <el-form-item label="恢复通知" prop="recoveryNotification">
              <el-switch v-model="formData.recoveryNotification" />
            </el-form-item>
            <el-form-item label="恢复模板" prop="recoveryTemplate" v-if="formData.recoveryNotification">
              <el-input
                v-model="formData.recoveryTemplate"
                type="textarea"
                :rows="2"
                placeholder="请输入恢复通知模板"
              />
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </el-form-item>

      <el-form-item label="规则描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入规则描述"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" v-if="dialogType !== 'view'">
          确定
        </el-button>
        <el-button type="success" @click="handleTest" v-if="dialogType !== 'add'">
          测试规则
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Minus } from '@element-plus/icons-vue'

interface Props {
  visible: boolean
  formData?: any
  dialogType: 'add' | 'edit' | 'view'
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'confirm'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  formData: () => ({}),
  dialogType: 'add'
})

const emit = defineEmits<Emits>()

const formRef = ref()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单数据
const formData = reactive({
  ruleName: '',
  warningType: '',
  warningLevel: '',
  status: 'active',
  thresholdConfig: [
    {
      parameter: '',
      operator: 'gt',
      value: '',
      unit: '',
      logic: 'and'
    }
  ],
  notificationMethod: [],
  notificationUsers: [],
  notificationGroups: [],
  triggerFrequency: 'immediate',
  duration: '',
  effectiveStartTime: '',
  effectiveEndTime: '',
  smsTemplate: '【水库预警】{ruleName}触发{level}，当前值：{value}，时间：{time}',
  emailTemplate: '预警规则"{ruleName}"触发{level}预警，当前监测值为{value}，触发时间：{time}。请及时处理。',
  recoveryNotification: false,
  recoveryTemplate: '预警规则"{ruleName}"已恢复正常，恢复时间：{time}',
  description: ''
})

// 表单验证规则
const formRules = {
  ruleName: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  warningType: [
    { required: true, message: '请选择预警类型', trigger: 'change' }
  ],
  warningLevel: [
    { required: true, message: '请选择预警级别', trigger: 'change' }
  ],
  notificationMethod: [
    { required: true, message: '请选择至少一种通知方式', trigger: 'change' }
  ],
  triggerFrequency: [
    { required: true, message: '请选择触发频率', trigger: 'change' }
  ]
}

// 获取对话框标题
const getDialogTitle = () => {
  const titleMap = {
    add: '新增预警规则',
    edit: '编辑预警规则',
    view: '查看预警规则'
  }
  return titleMap[props.dialogType]
}

// 获取参数选项
const getParameterOptions = () => {
  const typeMap = {
    water_level: [
      { label: '水位', value: 'water_level' },
      { label: '水位变化率', value: 'water_level_rate' }
    ],
    flow: [
      { label: '入库流量', value: 'inflow' },
      { label: '出库流量', value: 'outflow' },
      { label: '流量变化率', value: 'flow_rate' }
    ],
    rainfall: [
      { label: '1小时降雨量', value: 'rainfall_1h' },
      { label: '3小时降雨量', value: 'rainfall_3h' },
      { label: '24小时降雨量', value: 'rainfall_24h' },
      { label: '降雨强度', value: 'rainfall_intensity' }
    ],
    capacity: [
      { label: '库容', value: 'capacity' },
      { label: '库容利用率', value: 'capacity_rate' }
    ],
    comprehensive: [
      { label: '综合风险指数', value: 'risk_index' },
      { label: '安全系数', value: 'safety_factor' }
    ]
  }
  return typeMap[formData.warningType] || []
}

// 预警类型变化处理
const handleWarningTypeChange = () => {
  // 重置阈值配置
  formData.thresholdConfig = [
    {
      parameter: '',
      operator: 'gt',
      value: '',
      unit: '',
      logic: 'and'
    }
  ]
}

// 添加阈值条件
const addThresholdCondition = () => {
  formData.thresholdConfig.push({
    parameter: '',
    operator: 'gt',
    value: '',
    unit: '',
    logic: 'and'
  })
}

// 移除阈值条件
const removeThresholdCondition = (index: number) => {
  formData.thresholdConfig.splice(index, 1)
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 确认操作
const handleConfirm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      // 调用保存API
      saveWarningRule()
    }
  })
}

// 测试规则
const handleTest = () => {
  ElMessage.info('正在测试预警规则...')
  // 调用测试API
  testWarningRule()
}

// 保存预警规则
const saveWarningRule = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('保存成功')
    emit('confirm')
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 测试预警规则
const testWarningRule = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('规则测试通过')
  } catch (error) {
    ElMessage.error('规则测试失败')
  }
}

// 监听表单数据变化
watch(() => props.formData, (newData) => {
  if (newData && Object.keys(newData).length > 0) {
    Object.assign(formData, {
      ...newData,
      thresholdConfig: newData.thresholdConfig || [
        {
          parameter: '',
          operator: 'gt',
          value: '',
          unit: '',
          logic: 'and'
        }
      ]
    })
  }
}, { immediate: true, deep: true })

// 监听对话框显示状态
watch(dialogVisible, (visible) => {
  if (!visible) {
    // 重置表单
    formRef.value?.resetFields()
  }
})
</script>

<style scoped>
.threshold-config {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
}

.threshold-item {
  margin-bottom: 10px;
}

.threshold-item:last-child {
  margin-bottom: 0;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-collapse-item__header) {
  font-size: 14px;
  font-weight: normal;
}

:deep(.el-collapse-item__content) {
  padding-bottom: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}
</style>